package com.tianlang.security;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.stereotype.Component;

import com.tianlang.cache.Cache;
import com.tianlang.domain.pojo.Authority;
import com.tianlang.domain.pojo.Role;
import com.tianlang.service.IBaseManager;
import com.tianlang.util.StringUtil;

/**
 * 
 * @author mcp
 *
 */
@Component
public class SecurityReLoad {

	private static final Logger log = Logger.getLogger(SecurityReLoad.class);

	@Autowired
	private IBaseManager baseManager;

	/**
	 * 修改资源（权限）与角色之间的对应关系时可主动调用，重新加载
	 * 
	 * @param authorityId
	 */
	public void reLoadResourceDefine(String authorityId) {
		Authority authority = (Authority) baseManager.getObject(Authority.class, authorityId);
		String url = authority.getName();
		List<Role> roles = authority.getRoles();
		Collection<ConfigAttribute> attributes = new ArrayList<ConfigAttribute>();
		for (Role role : roles) {
			String auth = role.getTag();
			if (StringUtil.isNotEmpty(auth)) {
				ConfigAttribute attribute = new SecurityConfig("ROLE_" + auth);
				attributes.add(attribute);
			}
		}
		Cache.resourceMap.put(url, attributes);
		log.info("权限与角色重加载完成。。。。。。");
	}
}
